Implicit and Explicit Route Model Binding


1. Implicit Route Model Binding

// Define a route with implicit model binding
Route::get('user/{user}', [UserController::class, 'show'])->name('user.show');

// In UserController
public function show(User $user)
{
    return view('user.show', compact('user'));
}

Route Definition: Route::get('user/{user}', [UserController::class, 'show']) automatically resolves the User model for the {user} parameter using its primary key.

Controller Method: Laravel injects the User model instance directly into the show method, simplifying code and avoiding manual query logic.

2. Explicit Route Model Binding

// Define a route with explicit model binding
Route::get('post/{post}', [PostController::class, 'show'])->name('post.show');

// In AppServiceProvider 
public function boot()
{
    parent::boot();
    Route::bind('post', function ($value) {
        return Post::where('slug', $value)->firstOrFail();
    });
}

// In PostController
public function show(Post $post)
{
    return view('post.show', compact('post'));
}

Route Definition: Route::get('post/{post}', [PostController::class, 'show']) uses explicit binding to handle custom retrieval logic.

Custom Binding Logic: In AppServiceProvider, Route::bind('post', function ($value) { ... }) allows you to define how the model should be resolved, such as using a non-primary key (e.g., slug).

Controller Method: Laravel injects the Post model instance, resolved by the custom logic, into the show method.

Difference

Implicit Binding: Automatically resolves models based on route parameters and primary keys, making code cleaner and easier to maintain.

Explicit Binding: Allows custom logic for model retrieval, offering more flexibility in how models are resolved.

You Might Also Like

Apply Select Statements for Efficient Data Retrieval

Retrieve only the necessary columns from the database to reduce memory usage and speed up queries. T...

Optimize Queries with Eager Loading

Reduce the number of database queries by using Eager Loading. Eager Loading helps you load related m...